package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.TravelComment;
import cn.wolfcode.wolf2w.query.TravelCommentQuery;
import cn.wolfcode.wolf2w.repository.TravelCommentRepository;
import cn.wolfcode.wolf2w.service.ITravelCommentService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService{

    @Autowired
    private TravelCommentRepository travelCommentRepository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(TravelComment travelComment) {
        travelComment.setId(null);
        travelComment.setCreateTime(new Date());
        if(StringUtils.hasLength(travelComment.getRefComment().getId())){
            //有值,说明是评论的评论
            TravelComment travelComment1 = this.get(travelComment.getRefComment().getId());
            travelComment.setRefComment(travelComment1);
        }
        //没有说明是普通评论
        travelCommentRepository.save(travelComment);
    }

    @Override
    public void delete(String id) {
        travelCommentRepository.deleteById(id);
    }

    @Override
    public void update(TravelComment travelComment) {

        travelCommentRepository.save(travelComment);
    }

    @Override
    public TravelComment get(String id) {
        TravelComment travelComment = travelCommentRepository.findById(id).orElse(null);
        return travelComment;
    }

    @Override
    public List<TravelComment> list() {

        return travelCommentRepository.findAll();
    }

    @Override
    public Page<TravelComment> queryPageList(TravelCommentQuery qo) {
        Query query = new Query();

        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.ASC,"_id");
        return DBHelper.query(template,TravelComment.class,query,pageable);
    }

    @Override
    public void commentThumb(String uid, String cid) {
        //首先判断评论类中的uid的List集合中是否有该id
        TravelComment travelComment = this.get(cid);
        //更新数据
        this.update(travelComment);
    }

    @Override
    public List<TravelComment> comments(TravelCommentQuery qo) {
        List<TravelComment> list = travelCommentRepository.findByTravelId(qo.getTravelId());
        return list;
    }

}
